﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Models;
using WinformDevFramework.Services.System;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WinformDevFramework
{
    public partial class FrmRole : BaseForm1
    {
        private IsysRoleServices _sysRoleServices;
        private IsysUserRoleServices _sysUserRoleServices;
        private ISysUserServices _sysUserServices;
        private IsysRoleMenuServices _sysRoleMenuServices;
        private ISysMenuServices _sysMenuServices;

        public FrmRole(IsysRoleServices sysRoleServices, IsysUserRoleServices sysUserRoleServices,
            ISysUserServices sysUserServices, IsysRoleMenuServices sysRoleMenuServices,
            ISysMenuServices sysMenuServices)
        {
            _sysRoleServices = sysRoleServices;
            _sysUserRoleServices = sysUserRoleServices;
            _sysUserServices = sysUserServices;
            _sysRoleMenuServices = sysRoleMenuServices;
            _sysMenuServices = sysMenuServices;
            InitializeComponent();
        }

        public override void Init()
        {
            base.Init();
            //初始化 数据列表 列名称
            this.dataGridViewList.DataSource = GetAllRoles();
            this.dataGridViewList.Columns["RoleName"].HeaderText = "角色名称";
            this.dataGridViewList.Columns["Remark"]!.HeaderText = "备注";
            this.dataGridViewList.Columns["CreateTime"].HeaderText = "创建时间";
            this.dataGridViewList.Columns["UpdateTime"].HeaderText = "修改时间";
            this.dataGridViewList.Columns["CreateBy"].Visible = false;
            this.dataGridViewList.Columns["UpdateBy"].Visible = false;
            uiTreeViewFunction.CheckBoxes = true;
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as sysRole;
            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.txtRoleName.Text = model.RoleName;
            this.txtRemark.Text = model.Remark;

            //设置可选择功能
            SetFunction();
            //设置用户
            SetUser();

            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);

            //设置可选择功能
            SetFunction();
            //设置用户
            SetUser();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);

        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            if (ValidateData())
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    //保存角色信息
                    sysRole newRole = new sysRole();
                    newRole.RoleName = txtRoleName.Text;
                    newRole.Remark = txtRemark.Text;
                    newRole.CreateBy = AppInfo.User.ID;
                    newRole.CreateTime = DateTime.Now;
                    var id = _sysRoleServices.Insert(newRole);
                    txtID.Text = id.ToString();
                    if (id > 0)
                    {
                        //保存 功能
                        List<sysRoleMenu> roleMenus = new List<sysRoleMenu>();
                        foreach (TreeNode node in uiTreeViewFunction.Nodes)
                        {
                            GetFunction(node, roleMenus);
                        }

                        var count = _sysRoleMenuServices.Insert(roleMenus);

                        //保存用户
                        List<sysUserRole> roleUsers = new List<sysUserRole>();
                        List<sysUser> users = (List<sysUser>)dataGridView1.DataSource;
                        foreach (var sysUser in users)
                        {
                            sysUserRole roleUser = new sysUserRole();
                            roleUser.RoleID = int.Parse(txtID.Text);
                            roleUser.UserID = sysUser.ID;
                            roleUsers.Add(roleUser);
                        }

                        _sysUserRoleServices.Insert(roleUsers);
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                // 修改
                else
                {
                    sysRole role = _sysRoleServices.QueryById(int.Parse(txtID.Text));
                    role.RoleName = txtRoleName.Text;
                    role.Remark = txtRemark.Text;
                    role.UpdateBy = AppInfo.User.ID;
                    role.UpdateTime = DateTime.Now;
                    if (_sysRoleServices.Update(role))
                    {
                        //删除旧数据
                        _sysRoleMenuServices.Delete(p => p.RoleID == int.Parse(txtID.Text));
                        _sysUserRoleServices.Delete(p => p.RoleID == int.Parse(txtID.Text));

                        //保存功能
                        List<sysRoleMenu> roleMenus = new List<sysRoleMenu>();
                        foreach (TreeNode node in uiTreeViewFunction.Nodes)
                        {
                            GetFunction(node, roleMenus);
                        }

                        var count = _sysRoleMenuServices.Insert(roleMenus);

                        //保存用户
                        List<sysUserRole> roleUsers = new List<sysUserRole>();
                        List<sysUser> users = (List<sysUser>)dataGridView1.DataSource;
                        foreach (var sysUser in users)
                        {
                            sysUserRole roleUser = new sysUserRole();
                            roleUser.RoleID = int.Parse(txtID.Text);
                            roleUser.UserID = sysUser.ID;
                            roleUsers.Add(roleUser);
                        }

                        _sysUserRoleServices.Insert(roleUsers);
                        MessageBox.Show("保存成功！", "提示");
                    }
                }

                SetToolButtonStatus(formStatus);
                //var menus = GetAllUsers();
                this.dataGridViewList.DataSource = GetAllRoles();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            if (isAdd)
            {
                btnEdit.Enabled = false;
            }
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _sysRoleMenuServices.Delete(p => p.RoleID == int.Parse(txtID.Text));
                _sysUserRoleServices.Delete(p => p.RoleID == int.Parse(txtID.Text));
                _sysRoleServices.DeleteById(Int32.Parse(txtID.Text));
                SetToolButtonStatus(formStatus);
                var menus = GetAllRoles();
                this.dataGridViewList.DataSource = menus;
            }
        }

        public List<sysRole> GetAllRoles()
        {
            return _sysRoleServices.Query();
        }

        /// <summary>
        /// 设置功能按钮状态
        /// </summary>
        public override void SetToolButtonStatus(FormStatus status)
        {
            switch (status)
            {
                case FormStatus.Add:
                {
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = true;
                    SetControlStatus(this.groupBox1, true);
                    ClearControlsText(this.groupBox1);
                    break;
                }
                case FormStatus.Edit:
                {
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = true;
                    SetControlStatus(this.groupBox1, true);
                    break;
                }
                case FormStatus.View:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnSave.Enabled = false;
                    btnDel.Enabled = true;
                    btnCanel.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    uiTreeViewFunction.TreeView.ExpandAll();
                    SetTreeFunctionChecked();
                    break;
                }
                case FormStatus.Canel:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnSave.Enabled = false;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    break;
                }
                case FormStatus.First:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = false;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    break;
                }
                case FormStatus.Save:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnSave.Enabled = false;
                    btnDel.Enabled = true;
                    btnCanel.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    break;
                }
                case FormStatus.Del:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = false;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    ClearControlsText(this.groupBox1);
                    break;
                }
            }
        }

        //验证数据
        private bool ValidateData()
        {
            bool result = false;
            if (string.IsNullOrEmpty(txtRoleName.Text))
            {
                MessageBox.Show("角色名称不能为空！");
                return result;
            }

            result = true;
            return result;
        }

        /// <summary>
        /// 设置可选择功能
        /// </summary>
        private void SetFunction()
        {
            uiTreeViewFunction.Nodes.Clear();
            var allMenu = _sysMenuServices.Query();
            var hasMenuIDs = _sysRoleMenuServices.QueryListByClause(p =>
                    p.RoleID == int.Parse(string.IsNullOrEmpty(txtID.Text) ? "0" : txtID.Text))
                .Select(p => p.MenuID);

            uiTreeViewFunction.Nodes.Clear();
            List<TreeNode> nodes = new List<TreeNode>();
            foreach (var menu in allMenu)
            {
                TreeNode node = new TreeNode(menu.Title);
                node.Tag = menu;
                node.Name = menu.ID.ToString();
                if (hasMenuIDs.Contains(menu.ID))
                    node.Checked = true;
                nodes.Add(node);
            }

            foreach (var treeNode in nodes)
            {
                var menu = (sysMenu)treeNode.Tag;
                treeNode.Nodes.AddRange(nodes.Where(p => menu.ID == ((sysMenu)p.Tag).ParentID).ToArray());
            }

            uiTreeViewFunction.Nodes.Add(nodes.Where(p => ((sysMenu)p.Tag).ParentID == 0).FirstOrDefault());

        }

        /// <summary>
        /// 设置用户
        /// </summary>
        private void SetUser(string username = "")
        {
            //已拥有
            var userIds = _sysUserRoleServices.QueryListByClause(p =>
                    p.RoleID == int.Parse(string.IsNullOrEmpty(txtID.Text) ? "0" : txtID.Text))
                .Select(p => p.UserID);

            var users = _sysUserServices.QueryByIDs(userIds.Select(x => x ?? 0).ToArray());
            dataGridView1.DataSource = users;

            //未拥有
            var allUserIDs = _sysUserServices.Query().Select(p => p.ID);
            var noHasUserIDs = allUserIDs.Except(userIds.Select(x => x ?? 0)).ToList();
            var noHasUsers = _sysUserServices.QueryByIDs(noHasUserIDs.ToArray());
            if (!string.IsNullOrEmpty(username))
                noHasUsers = noHasUsers.Where(p => p.Username.Equals(username)).ToList();
            dataGridView2.DataSource = noHasUsers;

            SetDataGridView1Colums();
            SetDataGridView2Colums();

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SetUser(txtUserName.Text);
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            List<sysUser> userList = new List<sysUser>();
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                if (bool.Parse(row.Cells[0].Value?.ToString() ?? "false"))
                {
                    var user = row.DataBoundItem as sysUser;
                    userList.Add(user);
                }
            }

            if (!userList.Any())
            {
                MessageBox.Show("请至少选择一名用户");
                return;
            }

            var users = (List<sysUser>)dataGridView1.DataSource;
            dataGridView1.DataSource = null;
            if (users == null)
            {
                dataGridView1.DataSource = userList;
            }
            else
            {
                users.AddRange(userList);
                dataGridView1.DataSource = users;
            }

            SetDataGridView1Colums();

            //设置未拥有
            var user2 = (List<sysUser>)dataGridView2.DataSource;
            dataGridView2.DataSource = null;
            dataGridView2.Columns.Clear();
            dataGridView2.DataSource = user2.Except(userList).ToList();
            SetDataGridView2Colums();
        }

        /// <summary>
        /// 设置已拥有
        /// </summary>
        private void SetDataGridView1Colums()
        {
            this.dataGridView1.Columns["Username"]!.HeaderText = "账号";
            this.dataGridView1.Columns["Fullname"]!.HeaderText = "昵称";
            string[] cols = new[] { "Username", "Fullname" };
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.Visible = false;
                }
            }
        }

        /// <summary>
        /// 设置未拥有
        /// </summary>
        private void SetDataGridView2Colums()
        {
            string[] cols2 = new[] { "Username", "Fullname", "Sex", "Email", "PhoneNumber" };
            this.dataGridView2.Columns["Username"]!.HeaderText = "账号";
            this.dataGridView2.Columns["Fullname"]!.HeaderText = "昵称";
            this.dataGridView2.Columns["Sex"]!.HeaderText = "性别";
            this.dataGridView2.Columns["Email"]!.HeaderText = "邮箱";
            this.dataGridView2.Columns["PhoneNumber"]!.HeaderText = "电话号码";
            foreach (DataGridViewColumn column in dataGridView2.Columns)
            {
                if (!cols2.Contains(column.Name))
                {
                    column.Visible = false;
                }
            }

            // 添加一列用于显示多选框
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "";
            checkBoxColumn.Name = "checkBoxColumn";
            dataGridView2.Columns.Insert(0, checkBoxColumn);
        }

        /// <summary>
        /// 递归获取所选功能
        /// </summary>
        /// <returns></returns>
        private void GetFunction(TreeNode node, List<sysRoleMenu> roleMenus)
        {
            if (node.Checked)
            {
                sysRoleMenu menu = new sysRoleMenu();
                menu.RoleID = int.Parse(txtID.Text);
                menu.MenuID = int.Parse(node.Name);
                roleMenus.Add(menu);
            }

            foreach (TreeNode nodeNode in node.Nodes)
            {
                GetFunction(nodeNode, roleMenus);
            }
        }

        private void SetTreeFunctionChecked()
        {
            var allMenu = _sysMenuServices.Query();
            var hasMenuIDs = _sysRoleMenuServices.QueryListByClause(p =>
                    p.RoleID == int.Parse(string.IsNullOrEmpty(txtID.Text) ? "0" : txtID.Text))
                .Select(p => p.MenuID);
            foreach (var menu in hasMenuIDs)
            {
                var node = uiTreeViewFunction
                    .Nodes.Find(menu.ToString(), true).FirstOrDefault();
                node.Checked = true;
            }
        }
    }
}
